package com.xmall.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.xmall.define.dict.IsDefaultEnum;
import com.xmall.product.define.request.spu.SkuImageRequest;
import com.xmall.product.entity.SkuImage;
import com.xmall.product.mapper.SkuImageMapper;
import com.xmall.product.service.ISkuImageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.product.utils.ConvertUtils;
import com.xmall.utils.XmallUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 *  服务实现类
 */
@Service
public class SkuImageServiceImpl extends ServiceImpl<SkuImageMapper, SkuImage> implements ISkuImageService {

    /**
     * 保存
     */
    @Override
    public void save(Long spuId, Long skuId, List<SkuImageRequest> skuImageList) {
        if(CollectionUtil.isNotEmpty(skuImageList)) {
            skuImageList.forEach(skuImage -> {
                skuImage.setSpuId(spuId);
                skuImage.setSkuId(skuId);
            });
            this.saveBatch(ConvertUtils.SkuImageModule.INSTANCE.toEntityList(skuImageList));
        }
    }

    /**
     * 获取默认图片
     */
    @Override
    public String getDefaultImage(List<SkuImageRequest> images) {
        XmallUtils.notEmpty(images);
        Optional<SkuImageRequest> defaultImage = images.stream().filter(image -> IsDefaultEnum.YES.getValue() == image.getIsDefault()).findAny();
        if(!defaultImage.isPresent()) {
            images.get(0).setIsDefault(IsDefaultEnum.YES.getValue());
            return images.get(0).getUrl();
        }else {
            return defaultImage.get().getUrl();
        }
    }
}
